package com.cupk.inspection.service;

import com.cupk.inspection.model.InspectionRecord;
import com.cupk.inspection.repository.InspectionRecordRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class InspectionRecordService {

    private final InspectionRecordRepository recordRepository;

    public InspectionRecordService(InspectionRecordRepository recordRepository) {
        this.recordRepository = recordRepository;
    }

    /**
     * 创建巡检记录
     * @param record 包含taskId和deviceStatus的记录对象
     * @return 新创建的巡检记录
     * @throws IllegalArgumentException 当参数校验不通过时抛出
     */
    public InspectionRecord createRecord(InspectionRecord record) {
        validateCreateParameters(record);
        return recordRepository.save(buildCompleteRecord(record));
    }

    private void validateCreateParameters(InspectionRecord record) {
        if (record.getTaskId() == null) {
            throw new IllegalArgumentException("taskId不能为空");
        }
        if (!"正常".equals(record.getDeviceStatus()) && !"异常".equals(record.getDeviceStatus())) {
            throw new IllegalArgumentException("deviceStatus只能是'正常'或'异常'");
        }
        if ("异常".equals(record.getDeviceStatus()) && StringUtils.isEmpty(record.getAbnormalDescription())) {
            throw new IllegalArgumentException("异常状态必须提供abnormalDescription");
        }
    }

    private InspectionRecord buildCompleteRecord(InspectionRecord record) {
        record.setCompletionTime(new Timestamp(System.currentTimeMillis()));
        return record;
    }

    /**
     * 分页查询巡检记录
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @param deviceId 设备ID（可选）
     * @param startDate 开始时间（可选）
     * @param endDate 结束时间（可选）
     * @return 分页结果
     */
    public Page<InspectionRecord> getRecords(
            Integer page,
            Integer size,
            Long deviceId,
            Timestamp startDate,
            Timestamp endDate
    ) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return recordRepository.findByParams(deviceId, startDate, endDate, pageable);
    }
    /**
     * 根据ID查询单条记录
     * @param id 记录ID
     * @return 可选的巡检记录对象
     */
    public Optional<InspectionRecord> getRecordById(Long id) {
        return recordRepository.findById(id);
    }

    /**
     * 删除巡检记录
     * @param id 记录ID
     */
    public void deleteRecord(Long id) {
        recordRepository.deleteById(id);
    }
}
    